package model

import (
	"errors"
	"time"
)

type Section struct {
	Id         int64
	Name       string
	Duration   int32
	CreatedAt  time.Time `xorm:"created"`
	UpdatedAt  time.Time `xorm:"updated"`
	TotalScore int32
	EveryScore float32
	Deduct     bool
	Qids       []int64
	Group      int32
	Type       string
}

func (s *Section) SomeAsc(ids []int64) ([]Section, error) {
	var sections []Section
	err := orm.In("id", ids).Asc("id").Find(&sections)
	return sections, err
}

func (s *Section) SomeDesc(ids []int64) ([]Section, error) {
	var sections []Section
	err := orm.In("id", ids).Desc("id").Find(&sections)
	return sections, err
}

func (s *Section) OneById() error {
	ok, err := orm.ID(s.Id).Get(s)
	if !ok {
		return errors.New(SectionNotFound)
	}
	return err
}

func (s *Section) Create() error {
	ok, err := orm.Insert(s)
	if ok == 0 {
		return errors.New(SectionCreateFailed)
	}
	return err
}

func (s *Section) Page(num, size int32, desc bool, order string) ([]Section, error) {
	length := int(size)
	start := (int(num) - 1) * length
	if length == 0 {
		length = 5
	}
	var sections []Section
	o := orm.Limit(length, start)
	if order == "" {
		order = "id"
	}
	if desc {
		o.Desc(order)
	} else {
		o.Asc(order)
	}
	err := o.Find(&sections)
	return sections, err
}

func (s *Section) CountAll() (int64, error) {
	return orm.Count(s)
}

func (s *Section) Count() (int64, error) {
	return orm.Where("enable = ?", true).Count(s)
}

func (s *Section) AddQuestion(qid int64) error {
	s.Qids = append(s.Qids, qid)
	ok, err := orm.ID(s.Id).Cols("qids").Update(s)
	if ok == 0 {
		return errors.New(SectionUpdateFailed)
	}
	return err
}
